<template>
  <div class="container" :class="{'white-bg': activeName === 'first', 'pink-bg': activeName === 'second'}">
    <el-tabs v-model="activeName" class="custom-tabs" @tab-click="handleClick">
      <el-tab-pane label="结果列表" name="first" class="tab-content">
        <div class="filter-section">
          <el-select v-model="Prefecture" placeholder="选择地市" class="filter-select">
            <el-option
              v-for="item in Prefectures"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          
          <el-select v-model="city" placeholder="选择区县" class="filter-select">
            <el-option
              v-for="item in citys"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          
          <el-select v-model="task" placeholder="任务类型" class="filter-select">
            <el-option
              v-for="item in tasks"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          
          <el-select v-model="state" placeholder="任务状态" class="filter-select">
            <el-option
              v-for="item in states"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          
          <el-select v-model="type" placeholder="通信塔类型" class="filter-select">
            <el-option
              v-for="item in towerTypeList"
              :label="item.towerType.typeName"
              :value="item.towerType.id"
            />
          </el-select>
          
          <el-select v-model="Audit" placeholder="审核状态" class="filter-select">
            <el-option
              v-for="item in Audits"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <div class="search-section">
          <el-input v-model="input" class="search-input" placeholder="巡视任务名称" />
          <el-date-picker
            v-model="value2"
            type="datetimerange"
            class="date-picker"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-button  style="background-color: rgba(110, 78, 208, 0.1); border-color: #6f42c1; color: rgb(110, 78, 208);" class="search-btn" type="primary" @click="filterUser">查询</el-button>
        </div>

        <el-table :data="displayedData" class="data-table">
          <el-table-column label="序号" width="70">
            <template #default="{ row, $index }">
              <span v-if="row.inspectionTaskResult?.id" class="index-number">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
              <span v-else class="empty-index">{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="selectInspectionTaskResp.inspectionTask.taskName" label="任务名称" width="140">
            <template #default="{ row }">
              <span v-if="row.inspectionTaskResult?.id" class="table-text">{{ row.selectInspectionTaskResp.inspectionTask.taskName }}</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="selectInspectionTaskResp.inspectionTask.taskType" label="任务类型" width="100">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.selectInspectionTaskResp.inspectionTask.taskType }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="通信塔类型" width="110">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.selectInspectionTaskResp.towerType.typeName }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="地市" width="70">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.selectInspectionTaskResp.tower.city }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="区县" width="70">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.selectInspectionTaskResp.tower.county }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="巡视人" width="70">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.selectInspectionTaskResp.user.name }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="任务状态" width="90">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.selectInspectionTaskResp.inspectionTask.taskStatus }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="巡视进度" width="90">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.inspectionProgress }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="审核状态" width="90">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.inspectionTaskResult.auditStatus}}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="缺陷图片数/总图片数" width="100">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: red;">{{ row.inspectionTaskResult.abnormalPictureNumber }}</span>
      <span v-if="row.inspectionTaskResult?.id" style="color: black;">/{{ row.inspectionTaskResult.totalPictureNumber}}</span>
    </template>
  </el-table-column>
  <el-table-column prop="role.typeName" label="执行时间" width="100">
    <template #default="{ row }">
      <span v-if="row.inspectionTaskResult?.id"  style="color: black;">{{ row.selectInspectionTaskResp.inspectionTask.inspectionDate}}</span>
    </template>
  </el-table-column>   
          <el-table-column fixed="right" label="操作" min-width="160">
            <template #default="{ row }">
              <div v-if="row.inspectionTaskResult?.id" class="action-buttons">
                <el-button link type="primary" size="small" @click="getAllInspectionTaskResultDetail(row?.inspectionTaskResult?.id)"   v-if="hasPermission(authStore.permissions,6)" style="color: rgb(110, 78, 208);">查看详情</el-button>
                <el-button link type="primary" size="small" @click="upload1(row?.inspectionTaskResult?.id,currentFlag)"  v-if="hasPermission(authStore.permissions,7)" style="color: rgb(110, 78, 208);">导出报告</el-button>
                <el-button link type="primary" size="small" @click="upload(row.selectInspectionTaskResp.inspectionTask.typeName,row.selectInspectionTaskResp.inspectionTask.id)"  :disabled=" row.selectInspectionTaskResp?.inspectionTask?.reportStatus != 'S'"   v-if="hasPermission(authStore.permissions,7)" style="color: rgb(110, 78, 208);">下载报告</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          class="custom-pagination"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          layout="prev, pager, next, jumper"
          :background="true"
          @current-change="handleCurrentChange"
        />
      </el-tab-pane>

      <el-tab-pane label="结果详情" name="second" class="tab-content" :disabled="!canViewDetail">
        <div class="task-detail-container two-column">
          <div class="left-panel merged-panel">
            <div class="section-title">通信塔与巡检信息</div>
            <div class="info-grid">
              <div class="info-item">地市：<span class="highlight">{{ AllInspectionTaskResultDetail?.tower?.city }}</span></div>
              <div class="info-item">区县：<span class="highlight">{{ AllInspectionTaskResultDetail?.tower?.county }}</span></div>
              <div class="info-item">经度：<span class="highlight">{{ AllInspectionTaskResultDetail?.tower?.longitude }}</span></div>
              <div class="info-item">纬度：<span class="highlight">{{ AllInspectionTaskResultDetail?.tower?.latitude }}</span></div>
              <div class="info-item">安装位置：<span class="highlight">{{ AllInspectionTaskResultDetail?.tower?.installationPosition}}</span></div>
              <div class="info-item">巡视人员：<span class="highlight">{{ AllInspectionTaskResultDetail?.user?.name }}</span></div>
              <div class="info-item">通信塔名称：<span class="highlight">{{ AllInspectionTaskResultDetail?.tower?.towerName }}</span></div>
              <div class="info-item">任务名称：<span class="highlight">{{AllInspectionTaskResultDetail?.inspectionTask?.taskName }}</span></div>
              <div class="info-item">审核状态：<span class="highlight status-red">{{AllInspectionTaskResultDetail?.inspectionTaskResult?.auditStatus }}</span></div>
            </div>

            <div class="button-group">
              <el-button type="primary" class="action-btn"   @click="dialogVisible = true" v-if="hasPermission(authStore.permissions,8)">上报缺陷</el-button>
              <el-button type="primary" class="action-btn"   @click="upload1(AllInspectionTaskResultDetail?.inspectionTaskResult?.id,currentFlag)" v-if="hasPermission(authStore.permissions,8)">导出报告</el-button>
              <el-button type="primary" class="action-btn"  @click="upload(AllInspectionTaskResultDetail?.inspectionTask?.taskName, AllInspectionTaskResultDetail?.inspectionTask?.id)" :disabled="AllInspectionTaskResultDetail?.inspectionTask?.reportStatus != 'S'"  v-if="hasPermission(authStore.permissions,9)">下载报告</el-button>
            </div>

            <el-table :data="expandedData" class="position-table" border>
              <el-table-column label="拍摄部位" prop="positionName" width="120" />
              <el-table-column label="层/面数" width="80">
              <template #default="{ row }">
                <span v-if="row.layer">第{{ row.layer }}层/面</span>
                <span v-else>—</span>
              </template>
            </el-table-column>
  <el-table-column label="照片编号">
    <template #default="{ row }">
      <div class="picture-tags">
        <el-button
          v-for="(shortNum, index) in row.shortPictureIDs"
          :key="row.fullPictureIDs[index]"
          class="picture-tag"
          :class="{
            active: selectedPicture?.picNum == row.fullPictureIDs[index] &&
            selectedPicture?.positionName == row.positionName
          }"
            @click="handleClickPicture({ positionName: row.positionName }, row.fullPictureIDs[index])"
          >
  {{ shortNum }}
</el-button>
      </div>
    </template>
  </el-table-column>
</el-table>
<div class="section-title">结果摘要</div>
<ul class="summary-list">
  <div v-for="(items, partName) in AllInspectionTaskResultDetail?.resultDetailRespMap" :key="partName">
    <div v-for="item in items" :key="item.inspectionTaskResultDetail?.id">
      <div v-if="item.manualReviews[0]" class="summary-item">
        📷 {{ partName }} -
        <template v-if="/^\d+-\d+$/.test(item.inspectionTaskResultDetail.pictureID)">
          {{ item.inspectionTaskResultDetail.pictureID.split('-')[0] }}层/面 编号{{ item.inspectionTaskResultDetail.pictureID.split('-')[1] }}：
        </template>
        <template v-else>
          编号{{ item.inspectionTaskResultDetail.pictureID }}：
        </template>
        <span
          class="status-red"
          :style="{ 'color': item.manualReviews[0].defectContent == '无缺陷' ? 'green' : 'red' }"
        >
          {{ item.manualReviews[0].defectContent }}
        </span>
      </div>
    </div>
  </div>
</ul>

          </div>

          <div class="right-panel">
            <div class="section-title">图像分析</div>
            <div class="image-viewer">
              <el-image
                ref="elImageRef"
                @load="handleImageLoad"
                class="main-image"
                :src="selectedPictures"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                fit="cover"
                show-progress
              />
              <canvas ref="canvasOverlayRef" class="canvas-overlay"></canvas>
            </div>

            <div v-if="selectedStratus === '正常'" class="status-card normal">
              <div class="status-icon">✓</div>
              <div class="status-text">未发现异常，一切正常</div>
            </div>
            
            <div v-else-if="selectedStratus === '解析中'" class="status-card analyzing">
              <div class="status-icon">⏳</div>
              <div class="status-text">分析中，请稍后</div>
            </div>
            
            <div v-else-if="selectedStratus === '待审核'" class="status-card pending">
              <el-form class="audit-form" label-width="80px" label-position="left">
                <div class="info-item">缺陷内容：<span class="highlight"   :style="{ 'color': selectedItem.defectContent == '无缺陷' ? 'green': 'red' }">{{selectedItem.defectContent}}</span></div>
                <el-form-item label="结果校验">
                  <el-radio-group v-model="resultType">
                    <el-radio label="缺陷">缺陷</el-radio>
                    <el-radio label="误报">误报</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="缺陷等级">
                  <el-select v-model="trouble" placeholder="选择等级" style="width: 100%">
                    <el-option v-for="item in troubleList" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="textarea" type="textarea" rows="3" placeholder="请输入备注信息" />
                </el-form-item>
                <el-form-item style="text-align: center">
                  <el-button type="primary" @click="submitAndRefresh" v-if="hasPermission(authStore.permissions,10)">提交</el-button>
                </el-form-item>
              </el-form>
            </div>
            
            <div v-else-if="selectedStratus === '已审核'" class="status-card audited">
              <div class="info-item">缺陷内容：<span class="highlight"  :style="{ 'color': selectedItem.defectContent == '无缺陷' ? 'green': 'red' }">{{selectedItem.defectContent}}</span></div>
              <div class="info-item">结果校验：<span class="highlight status-red">{{selectedItem.resultCheck}}</span></div>
              <div class="info-item">缺陷等级：<span class="highlight status-green">{{ selectedItem.defectLevel }}</span></div>
              <div class="info-item">备注：<span class="highlight">{{ selectedItem.checkDescription }}</span></div>
              <div class="info-item">审核人：<span class="highlight">{{ selectedItem.auditPerson }}</span></div>
            </div>
          </div>
        </div>


        <el-dialog v-model="dialogVisible" title="上报巡视缺陷" width="900px">
      <div class="form-container">
        <div class="form-section">
          <el-divider content-position="left">缺陷基本信息</el-divider>
          <el-form :model="form" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="巡视任务：" required>
                  <el-select v-model="AllInspectionTaskResultDetail.inspectionTask.taskName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="通信塔部位：" required>
                  <el-select v-model="formPosition.towerPart" placeholder="选择部位">
                    <el-option v-for="(label, value) in towerPartOptions" :label="label" :value="value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="照片编号：">
                  <el-select v-model="formPosition.pictureId" placeholder="选择照片 ID">
                    <el-option v-for="(detailID, pictureID) in pictureIds" :label="pictureID" :value="detailID" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <el-divider content-position="left">缺陷信息</el-divider>
          <el-form :model="form" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="缺陷内容：" required>
                  <el-input v-model="troubleMessage" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="缺陷等级：" required>
                  <el-select v-model="troubleOne" placeholder="选择缺陷等级">
                    <el-option v-for="item in troubleList" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="缺陷位置：" required>
              <el-button type="info" @click="clearDefectArea">清除框选区域</el-button>
              <el-button type="info" @click="startCanvas">开始绘制</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="image-container">
          <el-image style="width: 100%;" :src="selectedImageUrl" fit="cover" />
          <canvas v-if="selectedImageUrl" ref="canvasRef" class="canvas-overlay" @mousedown="handleMouseDown" @mousemove="handleMouseMove" @mouseup="handleMouseUp" />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="uploadCanvasImage">上报</el-button>
        </div>
      </template>
    </el-dialog>




      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script lang="ts" setup>
    import { ref ,onMounted ,computed,nextTick , onUnmounted } from 'vue'
    import request from '@/utils/request';
    import { useAuthStore } from '@/stores/user';
    import type { TabsPaneContext } from 'element-plus'
    import { ElMessage } from 'element-plus'
    import showMessage from '@/utils/showMessage';
    import { useReportStore } from '@/stores/reportFlag'
    import type { ReportFlag } from '@/stores/reportFlag'
    import { hasPermission } from '@/utils/permissionUtils';

    const canViewDetail = ref(false); // 默认不可点

    const reportStore = useReportStore()
    // 获取当前值
    const currentFlag: ReportFlag = reportStore.reportFlag

    const canvasOverlayRef = ref<HTMLCanvasElement | null>(null); // 右侧图片上的 canvas
    const autoDefects = ref<any[]>([]); // 自动识别的缺陷信息
    const elImageRef = ref();

    const authStore = useAuthStore();//使用store仓库进行数据管理
    const activeName = ref('first')
    const resultType = ref()
    const value2 = ref()
    const dialogVisible = ref(false)
    const Prefecture = ref('阜阳市')  //地市
    const textarea = ref('')

    const form = ref({
      task: "",
      towerPart: "",
      photoNumber: "",
      defectContent: "",
      defectLevel: "",
    });
    const formPosition = ref({
    towerPart: null,
    pictureId: null,
    id:null
    });
  const Prefectures = [
      {
          value: '阜阳市',
          label: '阜阳市',
      },
  ]
  const city = ref()
  const citys = [
      {
          value: '颍州区',
          label: '颍州区',
      },
      {
          value: '颍东区',
          label: '颍东区',
      },
      {
          value: '颍泉区',
          label: '颍泉区',
      },
      {
          value: '临泉区',
          label: '临泉区',
      },
      {
          value: '太和县',
          label: '太和县',
      },
      {
          value: '阜南县',
          label: '阜南县',
      },
      {
          value: '颍上县',
          label: '颍上县',
      },
      {
          value: '界首市',
          label: '界首市',
      },
  ]
  const trouble = ref()
  const troubleOne = ref()
  const troubleMessage = ref()

  const troubleList = [
    {
      value:'一般',
      label:'一般'
    },
    {
      value:'严重',
      label:'严重'
    },
    {
      value:'危机',
      label:'危机'
    }
  ]
  const task = ref()
  const tasks = [
      {
          value: '例行巡检',
          label: '例行巡检',
      },
      {
          value: '自定义巡检',
          label: '自定义巡检',
      },
  ]
  const state = ref()
  const states = [
      {
          value: '未下发',
          label: '未下发',
      },
      {
          value: '待执行',
          label: '待执行',
      },
      {
          value: '执行中',
          label: '执行中',
      },
      {
          value: '已完成',
          label: '已完成',
      },
      {
          value: '执行失败',
          label: '执行失败',
      },
  ]
  const Audit = ref()
  const Audits = [
      {
          value: '待审核',
          label: '未下发',
      },
      {
          value: '待执行',
          label: '待执行',
      },
      {
          value: '执行中',
          label: '执行中',
      },
  ]
      // 切换按钮
      const handleClick = (tab: TabsPaneContext, event: Event) => {
  if (tab.paneName === 'second' && !canViewDetail.value) {
    event.preventDefault?.();
    return;
  }

  if (tab.paneName === 'first') {
    currentPage.value = 1;
    getAllTowerType();
    getAllInspectionTaskResult();
  }
};

      // 查看详情按钮
      const secondPageData = ref()
      const changeAlgorithm  = (data:any) => {
        activeName.value = 'second'
        secondPageData.value = data
      }


      // 获取全部任务信息
        const type = ref<any>()
        const towerTypeList = ref()
        const getAllTowerType = () => {
          request.get('/resource/getAllTowerType').then((res)=> {
          towerTypeList.value  = res.data
          })
        }
        const getAllInspectionTaskResult = () => {
            request.get('/inspection/getAllInspectionTaskResult').then((res)=> {
              tableData.value = res.data
              total.value = res.data.length;
              updateDisplayedData();
        })
        }

        const AllInspectionTaskResultDetail =ref()
        const getAllInspectionTaskResultDetail = (id: number) => {
  if (!id) return;

  request.post('/inspection/getInspectionTaskResultDetailByResultID', { id }).then((res) => {
    AllInspectionTaskResultDetail.value = res.data;
    canViewDetail.value = true;
    activeName.value = 'second';

    nextTick(() => {
      const map = res.data.resultDetailRespMap;
      const firstKey = Object.keys(map)[0];
      if (firstKey) {
        const firstGroup = map[firstKey];
        if (firstGroup?.length > 0) {
          const firstItem = firstGroup[0];
          const pictureID = firstItem.inspectionTaskResultDetail?.pictureID;

          // ✅ 显式设置所有字段，避免 undefined
          selectedPicture.value = {
            positionName: firstItem.towerPosition?.positionName || '',
            picNum: pictureID || '',
            item: firstItem,
          };

          // ✅ 确保 handleClickPicture 也接收完整数据
          handleClickPicture(
            { positionName: firstItem.towerPosition?.positionName || '' },
            pictureID || ''
          );
        }
      }
    });
  });
};

          // 提取部位信息并且去重

      const towerPartOptions = computed(() => {
      const uniquePositions = new Set();
        Object.values(AllInspectionTaskResultDetail.value?.resultDetailRespMap).forEach((items:any) => {
          console.log(111111,items);
          
        items.forEach((item:any) => {
        uniquePositions.add(item.towerPosition?.positionName);
      });
      });

     // 返回 { value: label } 结构
      return Array.from(uniquePositions).reduce((acc:any, name:any) => {
       acc[name] = name; // 这里 key 和 label 都是 positionName
       return acc;
      }, {});
    }); 

    const layeredPositionMap = computed(() => {
  const result: Record<string, Record<string, string[]>> = {};

  const map = AllInspectionTaskResultDetail.value?.resultDetailRespMap || {};
  Object.entries(map).forEach(([positionName, value]) => {
    const items = value as any[]; // 显式断言为数组
    items.forEach(item => {
      const pictureID = item.inspectionTaskResultDetail?.pictureID;
      const match = pictureID?.match(/^(\d+)-(\d+)$/);
      if (match) {
        const layer = match[1];
        const number = match[2];
        if (!result[positionName]) result[positionName] = {};
        if (!result[positionName][layer]) result[positionName][layer] = [];
        result[positionName][layer].push(number);
      }
    });
  });

  return result;
});



    // 计算属性：获取所有的 pictureID 并去重
    const pictureIds = computed(() => {
  const map: Record<string, number> = {};

  Object.values(AllInspectionTaskResultDetail.value.resultDetailRespMap).forEach((items: any) => {
    items.forEach((item: any) => {
      const pictureID = item.inspectionTaskResultDetail?.pictureID;
      const detailID = item.inspectionTaskResultDetail?.id;

      if (pictureID && detailID) {
        map[pictureID] = detailID; // 以 pictureID 作为 key，id 作为 value
      }
    });
  });

  return map; // 返回一个对象 { "3": 2, "2": 5, "1": 1 }
});

  // 下载报告按钮
   // 下载报告
   const upload = (name:any,id:number) => {
    ElMessage({
    message: '正在下载，请稍后',
    type: 'warning',
  })
      request.post('/inspection/downloadReport',{id}, { responseType: 'arraybuffer' }).then(res => {
    // 创建一个 Blob 对象，指定文件类型为 Excel
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'});

    // 创建一个临时的下载链接
    const url = window.URL.createObjectURL(blob);

    // 创建一个下载链接元素
    const a = document.createElement('a');
    a.href = url;
    a.download = `${name}_Repost.docx`; // 指定下载文件的名称
    // 触发点击事件开始下载
    document.body.appendChild(a);
    a.click();

    // 下载完成后清除 URL 对象
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  }).catch(error => {
    console.error('下载模板失败:', error);
  });

      
  }

const selectedImageUrl = computed<string | null>(() => {
  const allItems = AllInspectionTaskResultDetail.value?.resultDetailRespMap
  ? Object.values(AllInspectionTaskResultDetail.value.resultDetailRespMap).flat()
  : [];

  const foundItem:any = allItems.find(
    (item:any) => item.inspectionTaskResultDetail?.id === formPosition.value.pictureId
  );
  return foundItem ? foundItem.inspectionTaskResultDetail.primaryImageUrl : null;
});



        const upload1 = (id:number,currentFlag:ReportFlag) => {
          console.log(id);
          
          ElMessage({
            message: '正在导出，请稍后',
            type: 'warning',
          })     
            request.post('/inspection/drawDocx',{
              id,
              model:currentFlag
            }).then((res:any)=>{
              showMessage(res)
              getAllInspectionTaskResult()
            })
        }

        // 处理数据，拆分 pictureNumber
        const expandedData = computed(() => {
  const result: {
    positionName: string;
    layer: string; // 可为空，表示单层
    shortPictureIDs: string[]; // 显示用编号
    fullPictureIDs: string[]; // 对应的完整 pictureID（点击用）
  }[] = [];

  const map = AllInspectionTaskResultDetail.value?.resultDetailRespMap || {};

  Object.entries(map).forEach(([positionName, value]) => {
    const items = value as any[];
    const layeredMap: Record<string, { shortIDs: string[], fullIDs: string[] }> = {};
    let hasLayer = false;

    items.forEach(item => {
      const pictureID = item.inspectionTaskResultDetail?.pictureID;
      const match = pictureID?.match(/^(\d+)-(\d+)$/); // 多层结构

      if (match) {
        hasLayer = true;
        const layer = match[1];
        const number = match[2];
        if (!layeredMap[layer]) layeredMap[layer] = { shortIDs: [], fullIDs: [] };
        layeredMap[layer].shortIDs.push(number);     // 显示用：编号
        layeredMap[layer].fullIDs.push(pictureID);   // 点击用：完整IDa
      }
    });

    if (hasLayer) {
      Object.entries(layeredMap).forEach(([layer, ids]) => {
        result.push({
          positionName,
          layer,
          shortPictureIDs: ids.shortIDs,
          fullPictureIDs: ids.fullIDs,
        });
      });
    } else {
      // 单层结构，直接展示
      const pictureIDs = items.map(i => i.inspectionTaskResultDetail?.pictureID);
      result.push({
        positionName,
        layer: '',
        shortPictureIDs: pictureIDs,
        fullPictureIDs: pictureIDs,
      });
    }
  });

  return result;
});




// 存储选中状态
const selectedPicture = ref<{
  positionName: string;
  picNum: string;
  item: any;
} | null>(null);

// 存储选中的图片数据
const selectedPictures = ref<string[]>([]);
const selectedStratus = ref<string>();
const selectedPicId = ref<string>();
const selectedItem = ref<any>();

// 处理点击事件
const handleClickPicture = (item: any, picNum: string) => {
  selectedPicture.value = {
    positionName: item.positionName,
    picNum,
    item,
  };

  const imageUrls: string[] = [];
  Object.values(AllInspectionTaskResultDetail.value.resultDetailRespMap).forEach((items: any) => {
    items.forEach((detailItem: any) => {
      if (detailItem.inspectionTaskResultDetail.pictureID === picNum) {
        imageUrls.push(detailItem.inspectionTaskResultDetail.primaryImageUrl);
        selectedItem.value = detailItem.manualReviews[0];
        selectedStratus.value = detailItem.manualReviews[0]?.auditStatus;        
        selectedPicId.value = detailItem.manualReviews[0]?.id;
      }
    });
  });

  selectedPictures.value = imageUrls;
  loadAutoDefects();
};


    // 提交缺陷按钮
    const sumitTrouble = () => {
   
        request.post('/inspection/auditResult',{
          id:Number(selectedPicId.value),//图片的信息
          auditPerson:authStore.user?.name,//人的名称
          resultCheck:resultType.value,//缺陷还是误报
          defectLevel:trouble.value,
          checkDescription:textarea.value,
        }).then((res:any)=> {
          if(res.data.status == 'success'){
          
            getAllInspectionTaskResult()
          }
        })
    }

    const submitAndRefresh = async () => {
  try {
    await sumitTrouble(); // 原有提交逻辑

    // 1. 立即更新 selectedItem 的审核状态信息（假设当前项就是刚提交的）
    selectedItem.value.resultCheck = resultType.value;
    selectedItem.value.defectLevel = trouble.value;
    selectedItem.value.checkDescription = textarea.value;
    selectedItem.value.auditPerson = authStore.user?.name;
    selectedItem.value.auditStatus = '已审核';

    // 2. 修改右下角显示状态
    selectedStratus.value = '已审核';

    ElMessage.success('提交成功，状态已刷新');
  } catch (err) {
    console.error('提交失败', err);
    ElMessage.error('提交失败，请重试');
  }
};



    const tableData = ref([]); // 原始数据
    const displayedData = ref([]); // 当前页显示的数据
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(6); // 每页条数
    const total = ref(0); // 总条数
    const input = ref('')
    // 筛选数据
    const filterUser = () => {
      request.post("/inspection/getInspectionTaskResultByCondition" ,{
        city: Prefecture.value || '',
        county: city.value || '',
        taskType: task.value || '',
        taskStatus: state.value || '',
        towerTypeID: type.value || '',
        taskName: input.value || '',
        auditstatus: Audit.value || '',
        startTime: (value2.value?.[0]) ? formatDateOne(value2.value[0]) : '',
        endTime: (value2.value?.[1]) ? formatDateOne(value2.value[1]) : '',
      }).then(
      (res)=>{
        if(res.status == 200){          
            tableData.value = res.data
            total.value = res.data.length;
            updateDisplayedData();
            }
            }
          )
    }


// 格式化时间方法
const formatDateOne = (date:any) => {
  let d = new Date(date);
  let year = d.getFullYear();
  let month = String(d.getMonth() + 1).padStart(2, '0');
  let day = String(d.getDate()).padStart(2, '0');
  let hours = String(d.getHours()).padStart(2, '0');
  let minutes = String(d.getMinutes()).padStart(2, '0');
  let seconds = String(d.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

  
// 更新显示的数据
const updateDisplayedData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  const currentData = tableData.value.slice(start, end);

  // 填充空行以确保表格显示10行
  displayedData.value = Array.from({ length: pageSize.value }, (_, index) => currentData[index] || {});
};

// 处理分页切换
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  updateDisplayedData();
};



// 这里是开始绘制canvas的部分

const rectangles = ref<{ x1: number; y1: number; x2: number; y2: number }[]>([]);

    // **2️⃣ 获取 canvas 相关的 ref**
const canvasRef = ref<HTMLCanvasElement | null>(null);
const ctx = ref<CanvasRenderingContext2D | null>(null);
const isDrawing = ref(false);

// **3️⃣ 记录矩形框坐标**
const startX = ref(0);
const startY = ref(0);
const endX = ref(0);
const endY = ref(0);

// **4️⃣ 开始绘制模式**
const isCanvasActive = ref(false);
// **初始化 Canvas**
const initCanvas = () => {
  nextTick(() => {
    if (canvasRef.value) {
      const canvas = canvasRef.value;
      canvas.width = canvas.offsetWidth;
      canvas.height = canvas.offsetHeight;
      ctx.value = canvas.getContext("2d");
    }
  });
};


// **5️⃣ 开始绘制**
const startCanvas = () => {
  isCanvasActive.value = true;
  initCanvas();
};

// **6️⃣ 鼠标按下（开始框选）**
const handleMouseDown = (event: MouseEvent) => {
  if (!isCanvasActive.value) return;
  isDrawing.value = true;
  startX.value = event.offsetX;
  startY.value = event.offsetY;
};

// **7️⃣ 鼠标移动（动态绘制框）**
const handleMouseMove = (event: MouseEvent) => {
  if (!isDrawing.value || !ctx.value) return;

  endX.value = event.offsetX;
  endY.value = event.offsetY;

  // 先清空 Canvas，再绘制所有已存的矩形
  redrawCanvas();

  // 画当前正在绘制的矩形
  ctx.value.strokeRect(
    startX.value,
    startY.value,
    endX.value - startX.value,
    endY.value - startY.value
  );
};


// **8️⃣ 鼠标松开（完成框选）**
const handleMouseUp = () => {
  isDrawing.value = false;

  // 计算矩形的 4 个坐标
  const rectX = Math.min(startX.value, endX.value);
  const rectY = Math.min(startY.value, endY.value);
  const rectX2 = Math.max(startX.value, endX.value);
  const rectY2 = Math.max(startY.value, endY.value);

  // 存入数组
  rectangles.value.push({ x1: rectX, y1: rectY, x2: rectX2, y2: rectY2 });

  // 重新绘制所有矩形
  redrawCanvas();
};

const redrawCanvas = () => {
  if (!ctx.value || !canvasRef.value) return;
  
  ctx.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height); // 清空画布

  ctx.value.strokeStyle = "red";
  ctx.value.lineWidth = 2;

  // 遍历并绘制所有矩形
  rectangles.value.forEach(rect => {
    if (!ctx.value) return;
    ctx.value.strokeRect(
      rect.x1,
      rect.y1,
      rect.x2 - rect.x1,
      rect.y2 - rect.y1
    );
  });
};



// **9️⃣ 清除框选区域**
const clearDefectArea = () => {
  rectangles.value = []; // 清空数组
  redrawCanvas(); // 重新绘制
};


// **🔟 获取并上传 Canvas 图像**
const uploadCanvasImage = async () => {
  
  // 现在有一个数据校验
  if(!formPosition.value.pictureId || !troubleOne.value || !troubleMessage.value || !rectangles.value){
    ElMessage.error('参数不全，无法上传')
    return
  }


  if (!canvasRef.value) return;

const canvas = canvasRef.value;
const imageDataUrl = canvas.toDataURL("image/png");

// 获取 canvas 当前渲染尺寸
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;

// 获取原始图片尺寸
const imgElement = canvas.closest(".image-container")?.querySelector("img") as HTMLImageElement;
const naturalWidth = imgElement?.naturalWidth || 0;
const naturalHeight = imgElement?.naturalHeight || 0;

// 计算缩放比例
const scaleX = canvasWidth / naturalWidth;
const scaleY = canvasHeight / naturalHeight;

console.log('缩放比例:', { scaleX, scaleY });

  

  try {
    const formData = new FormData();
    const blob = dataURLtoBlob(imageDataUrl);
    // formData.append("file", blob, "defect-area.png");
    if (formPosition.value.pictureId !== null) {
      formData.append("taskResultID", formPosition.value.pictureId);
    }
    if ( troubleOne.value !== null) {
      formData.append("defectLevel", troubleOne.value);
    }
    if ( troubleMessage.value !== null) {
      formData.append("defectContent", troubleMessage.value);
    }
    // 上传所有矩形框的坐标数据
    formData.append("defectInformation", JSON.stringify(rectangles.value));

    formData.append("canvasScale", String(scaleX));

    await request.post("/inspection/reportInspectionDefect", formData, {
      headers: { "Content-Type": "multipart/form-data" },
    }).then((res)=> {
      showMessage(res)
      dialogVisible.value = false
    });
  } catch (error) {
    console.error("上传失败", error);
  }
};


// **转换 dataURL 为 Blob**
const dataURLtoBlob = (dataURL: string): Blob => {
  const byteString = atob(dataURL.split(",")[1]);
  const arrayBuffer = new ArrayBuffer(byteString.length);
  const uintArray = new Uint8Array(arrayBuffer);

  for (let i = 0; i < byteString.length; i++) {
    uintArray[i] = byteString.charCodeAt(i);
  }

  return new Blob([uintArray], { type: "image/png" });
};

const handleImageLoad = () => {
  drawCanvasOverlayOne();
};
//更新坐标
const loadAutoDefects = () => {
  autoDefects.value = [];

  if (!selectedItem.value?.defectInformation) return;

  try {
    const parsed = JSON.parse(selectedItem.value.defectInformation); // 先解析 JSON

    autoDefects.value = parsed
      .filter((item: any) => item.result?.flag === 1)
      .flatMap((item: any) => {
        const messages = item.result?.message || [];
        return messages.map((msg: any) => ({
          label: msg.description,
          coordinate: msg.coordinate
        }));
      });
  } catch (e) {
    console.warn("解析 defectInformation 失败", e);
    autoDefects.value = [];
  }
};


//这个是绘制canvas相关的函数

const drawCanvasOverlayOne = () => {
  const canvas = canvasOverlayRef.value;
  const imgEl = elImageRef.value?.$el.querySelector('img') as HTMLImageElement;

  if (!canvas || !imgEl) {
    console.warn('canvas 或 image 元素未找到');
    return;
  }

  const displayWidth = imgEl.clientWidth;
  const displayHeight = imgEl.clientHeight;
  const naturalWidth = imgEl.naturalWidth;
  const naturalHeight = imgEl.naturalHeight;

  const scaleX = displayWidth / naturalWidth;
  const scaleY = displayHeight / naturalHeight;

  canvas.width = displayWidth;
  canvas.height = displayHeight;

  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.strokeStyle = 'red';
  ctx.lineWidth = 2;
  ctx.font = '12px Arial';
  ctx.fillStyle = 'red';

  autoDefects.value.forEach(item => {
    const { x1, y1, x2, y2 } = item.coordinate;

    // ⬇️ 缩放后的位置
    const left = Math.min(x1, x2) * scaleX;
    const top = Math.min(y1, y2) * scaleY;
    const w = Math.abs(x2 - x1) * scaleX;
    const h = Math.abs(y2 - y1) * scaleY;

    ctx.strokeRect(left, top, w, h);
    ctx.fillText(item.label, left + 4, top - 4);
  });
};

  const detectPageSize = () => {
  const width = window.innerWidth;
  pageSize.value = width <= 1800 ? 6 : 14; // ≤1200px 时显示10条，>1200px 时显示20条
  updateDisplayedData();
};

  onMounted(()=>{
    detectPageSize(); // 初始调用
    window.addEventListener('resize', detectPageSize); // 直接监听resize事件，不使用防抖
    initCanvas();
   
   getAllTowerType()

   getAllInspectionTaskResult()

  })
  onUnmounted(() => {
  window.removeEventListener('resize', detectPageSize); // 移除事件监听
});


</script>

<style scoped>
/* Base styles */
.container {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  width: 100%;
  height:calc(100vh - 100px) ;
}

.white-bg {
  background-color: #f5f7fa;
}

.pink-bg {
  background-color: #fff5f7;
}

/* Tabs styling */
.custom-tabs {
  background: rgb(255, 255, 255);
  border-radius: 12px;
  height: calc(100vh - 120px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  box-sizing: content-box;
}

.tab-content {
  padding: 15px;
}

/* Filter section */
.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.filter-select {
  width: 180px;
}

.filter-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
}

/* Search section */
.search-section {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  width: 240px;
}

.search-input .el-input__inner {
  border-radius: 8px;
}

.date-picker {
  width: 380px;
}

.search-btn {
  width: 100px;
  border-radius: 8px;
  font-weight: 500;
}

/* Table styling */
.data-table {
  width: 100%;
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.data-table th {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

.data-table td {
  padding: 12px 0;
}

.index-number {
  color: #606266;
  font-weight: 500;
}

.empty-index {
  color: transparent;
}

.table-text {
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

/* Pagination */
.custom-pagination {
  margin-top: 25px;
  justify-content: center;
}

.custom-pagination .btn-prev,
.custom-pagination .btn-next {
  border-radius: 6px;
}

.custom-pagination .number {
  border-radius: 6px;
}

/* Detail view styling */
.task-detail-container {
  height: calc(100vh - 160px); /* 控制整体高度 */
  display: flex;
  gap: 30px;
}

.left-panel {
  flex: 1;
  max-height: calc(100vh - 230px); /* 可视高度 */
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: auto;
  padding-bottom: 10px;
}

.right-panel {
  flex: 1;
  height: calc(100vh - 230px);
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: auto;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.info-item {
  font-size: 14px;
  color: #666;
}

.highlight {
  color: #333;
  font-weight: 500;
}

.status-red {
  color: #f56c6c;
}

.status-green {
  color: #67c23a;
}

.button-group {
  display: flex;
  gap: 15px;
  margin: 20px 0;
}

.action-btn {
  border-radius: 8px;
  padding: 10px 20px;
}

.position-table {
  width: 100%;
  margin: 15px 0;
  border-radius: 8px;
  overflow: hidden;
}
/* .position-table .picture-tags .picture-tag:first-child {
  background-color: #409eff;
  color: white;
} */

/* 正常选中状态 */
.position-table .picture-tags.picture-tag.active {
  background-color: #409eff !important;
  color: white !important;
}

.picture-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.picture-tag {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
}

/* 选中样式 */
.picture-tag.active {
  background-color: #409eff !important;
  color: white !important;
}

.summary-list {
  margin-top: 15px;
}

.summary-item {
  font-size: 14px;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

/* Image viewer */
.image-viewer {
  position: relative;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.main-image {
  width: 100%;
  border-radius: 8px;
}
.image-container {
  position: relative;
}

.canvas-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: auto; /* 必须打开鼠标交互 */
  z-index: 10;
}

/* Status cards */
.status-card {
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
}

.normal {
  background-color: #f0f9eb;
  color: #67c23a;
  text-align: center;
}

.analyzing {
  background-color: #ecf5ff;
  color: #409eff;
  text-align: center;
}

.pending {
  background-color: #fdf6ec;
  border: 1px solid #f5dab1;
}

.audited {
  background-color: #f0f9ff;
  border: 1px solid #d9ecff;
}

.status-icon {
  font-size: 24px;
  margin-bottom: 10px;
}

.status-text {
  font-size: 16px;
}

.audit-form {
  margin-top: 10px;
}
::v-deep(.el-table__row) {
  height: 60px !important;
}

::v-deep(.el-table__row .cell) {
  display: flex;
  align-items: center;
  height: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

</style>